<template>
  <div class="search">
    <van-nav-bar title="商品搜索" left-arrow @click-left="$router.go(-1)"/>
    <div class="search-bar">
      <van-search
        ref="searchInput"
        show-action shape="round"
        placeholder="搜索你要找的商品"
        v-model="searchValue"
        @search="onClickButton(searchValue)"
      >
        <template #action>
          <div @click="onClickButton(searchValue)">搜索</div>
        </template>
      </van-search>
    </div>
    <div class="search-history" v-show="searchValueList.length !== 0">
      <div class="history">
        <span>最近搜索</span>
        <van-icon name="delete-o" color="#777" @click="delHistory()"/>
      </div>
      <div class="history-list">
        <van-row
          type="flex"
          justify="start"
          align="center"
        >
          <van-col span="8" v-for="(value,index) in searchValueList" :key="index" @click="onClickButton(value)">{{
              value
            }}
          </van-col>
        </van-row>
      </div>

    </div>
  </div>
</template>

<script>

import { setSearchValue, getSearchHistory, delSearchHistory } from '@/api/search'

export default {
  data () {
    return {
      searchValue: '',
      searchValueList: '',
      categoryId: null
    }
  },
  methods: {
    onClickButton (value) {
      if (!value) {
        return
      }
      setSearchValue(value)
      this.getSearchValue()
      this.$router.push({
        path: '/search/list?',
        query: {
          goodsId: value,
          categoryId: this.categoryId
        }
      })
    },
    getSearchValue () {
      this.searchValueList = getSearchHistory()
    },
    delHistory () {
      delSearchHistory()
      this.getSearchValue()
    }
  },
  created () {
    this.categoryId = this.$route.query.categoryId
  },
  mounted () {
    this.getSearchValue()
    this.$nextTick(() => {
      const input = this.$refs.searchInput.querySelector('.van-field__control')
      input && input.focus()
    })
  }
}
</script>

<style lang="less" scoped>
.search {
  height: 1000px;
  background-color: #f6f6f6;

  .search-bar {
    margin: 10px 10px;

    .van-search {
      padding: 0 0;
    }

    .van-nav-bar {
      background-color: rgb(255 255, 255);
    }

    ::v-deep .van-search__action {
      background-color: #fa2209;
      border-radius: 0 7px 7px 0;
    }

    ::v-deep .van-search__content {
      background-color: rgb(255 255, 255);
    }
  }

  .search-history {
    margin: 0 10px;

    .history {
      display: flex;
      align-items: center;
      justify-content: space-between;

      span {
        font-size: 14px;
        color: #777;
      }
    }

    .history-list {
      margin: 10px 0;

      .van-row {
        row-gap: 10px;
      }

      .van-col {
        background-color: rgb(255 255, 255);
        text-align: center;
        border-radius: 10px;
        font-size: 14px;
        color: #777;
        margin-left: 3%;
        width: 30%;
      }
    }
  }
}
</style>
